import React, { useContext, useEffect, useState } from "react";
import {
  Layout,
  Input,
  InputNumber,
  Select,
  Form,
  Button,
  Cascader,
} from "antd";
import { UserOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd/es/form";
import { useLocation, useNavigate } from "react-router-dom";
import { ClientContext } from "../App";
import { getValue } from "../tools/getValue";
import { Wrapper } from "../components/Wrapper/index";

const { Option } = Select;

const layout = {
  labelCol: { span: 10, offset: 4 },
  wrapperCol: { span: 10, offset: 1 },
};

const tailLayout = {
  wrapperCol: { offset: 15, span: 8 },
};

interface Option {
  value: string | number;
  label: string;
  children?: Option[];
  disableCheckbox?: boolean;
}

export const INSERT = "insert";
const NAME = "name";
const AGE = "age";
const ID = "ID";
const ACADEMY = "academy";
const GENDER = "gender";
const SUPERVISOR = "supervisor";
const SCENE = "scene";

const InsertInfo: React.FC = () => {
  const { client } = useContext(ClientContext);

  // 检查是否是编辑模式
  const location = useLocation();
  const state = location.state;
  const isEdit = state && state.isEdit;
  let info = {};

  const navigate = useNavigate();

  const [scene, setScene] = useState<Option[]>([]);
  const sceneMap = new Map();
  const sceneIdMap = new Map();

  useEffect(() => {
    async function getScene() {
      const { changeMsg } = client.getProps();

      const { message, code, data } = await (
        await client.get("/get/scene")
      ).data;

      if (code == 0) {
        const sceneTmp: Option[] = [];

        const sceneReg = /(.*)\d/;
        data.scenes.map(({ id, ip, name }: any) => {
          sceneIdMap.set(id, name);

          const prexNameArr = name.match(sceneReg);
          if (prexNameArr == null) {
            return;
          }
          const prexName = prexNameArr[1];
          if (sceneMap.has(prexName)) {
            sceneMap.set(
              prexName,
              sceneMap.get(prexName).concat({ label: name, value: id })
            );
          } else {
            sceneMap.set(prexName, [{ label: name, value: id }]);
          }
        });

        sceneMap.forEach((value, key) => {
          sceneTmp.push({
            label: key,
            value: key,
            children: value,
          });
        });
        setScene(sceneTmp);

        if (isEdit) {
          const prefixScene: any[][] = [];
          console.log(state.info.privilege);

          state.info.privilege.map((id: any) => {
            console.log(id);

            if (id == "") {
              return;
            }
            const name = sceneIdMap.get(id);
            // console.log(name);

            const prexNameArr = name.match(sceneReg);
            if (prexNameArr == null) {
              return;
            }
            const prexName = prexNameArr[1];
            prefixScene.push([prexName, id]);
          });

          info = Object.assign({ scene: prefixScene }, state.info.detail);
          form.setFieldsValue(info);
        }
      }
    }
    getScene();
  }, []);

  const formRef = React.useRef<FormInstance>(null);
  const [form] = Form.useForm();

  const onFinish = async () => {
    const { changeMsg } = client.getProps();
    try {
      const token = client.getToken();
      const formData = form.getFieldsValue();
      const { scene: scenes, ...detail } = formData;

      const privilege: string[] = [];
      // 场景信息收集
      scenes?.map((item: any) => {

        if (item.length == 1) {
          const { children }: any = scene.find(({ value }) => value == item[0]);
          children.map(({ value }: any) => {
            privilege.push(value);
          });
          return;
        }

        privilege.push(item[1]);
      });

      let req = {};
      if (isEdit) {
        console.log(detail);
        
        req = {
          token,
          key: state.info.key,
          privilege: privilege.join(","),
          info: JSON.stringify(detail),
        };

        const { code, message } = await (
          await client.post("/post/info/update", req)
        ).data;
        if (code != 0) {
          changeMsg({ msg: message });
          return;
        }
        changeMsg({ msg: message, code });
        navigate("/index/info", { replace: false });
        return;
      }

      req = {
        token,
        privilege: privilege.join(","),
        info:JSON.stringify(detail),
      };

      const { code, message } = await (
        await client.post("/post/info/insert", req)
      ).data;

      if (code != 0) {
        changeMsg({ msg: "请检查填写字段" });
        return;
      }
      changeMsg({ msg: message, code });
      navigate("/index/info", { replace: false });
      return;
    } catch (errorInfo) {
      changeMsg({ msg: errorInfo });
    }
  };

  const onReset = () => {
    const formData = form.getFieldsValue();   
    formRef.current?.resetFields();

    if(isEdit){
      const { name, ID, gender} = formData;
      form.setFieldsValue({ name, ID, gender})
    }
  };

  useEffect(() => {}, [scene]);

  // 组件数组
  // TODO: 校验函数
  const components = [
    {
      name: "NAME",
      key: NAME,
      label: getValue([INSERT, NAME]),
      validator: validate("zh"),
      rules:[{ required: true, message: "该项不能为空" }],
      tooltip: getValue(["tooltips", INSERT, NAME]),
      Component: Input,
      props: {
        disabled: isEdit,
      },
    },
    {
      name: "AGE",
      key: AGE,
      label: getValue([INSERT, AGE]),
      //validator: "",
      rules:[{ required: true, message: "该项不能为空" }],
      tooltip: getValue(["tooltips", INSERT, AGE]),
      Component: InputNumber,
      props: {
        max: 150,
        min: 0,
      },
    },
    {
      name: "ID",
      key: ID,
      label: getValue([INSERT, ID]),
      //validator: "",
      rules:[{ required: true, message: "该项不能为空" }],
      tooltip: getValue(["tooltips", INSERT, ID]),
      Component: Input,
      props: {
        prefix: <UserOutlined />,
        disabled: isEdit,
      },
    },
    {
      name: "ACADEMY",
      key: ACADEMY,
      label: getValue([INSERT, ACADEMY]),
      //validator: "",
      rules:[{ required: true, message: "该项不能为空" }],
      tooltip: getValue(["tooltips", INSERT, ACADEMY]),
      Component: Select,
      props: {
        placeholder: "选择学院",
        options: [
          { label: "航空学院", value: "航空学院" },
          { label: "航天学院", value: "航天学院" },
          { label: "航海学院", value: "航海学院" },
          { label: "材料学院", value: "材料学院" },
          { label: "机电学院", value: "机电学院" },
          { label: "力学与土木建筑学院", value: "力学与土木建筑学院" },
          { label: "动力与能源学院", value: "动力与能源学院" },
          { label: "电子信息学院", value: "电子信息学院" },
          { label: "自动化学院", value: "自动化学院" },
          { label: "计算机学院", value: "计算机学院" },
          { label: "数学与统计学院", value: "数学与统计学院" },
          { label: "物理科学与技术学院", value: "物理科学与技术学院" },
          { label: "化学与化工学院", value: "化学与化工学院" },
          { label: "管理学院", value: "管理学院" },
          { label: "公共政策与管理学院", value: "公共政策与管理学院" },
          { label: "软件学院", value: "软件学院" },
          { label: "生命学院", value: "生命学院" },
          { label: "外国语学院", value: "外国语学院" },
          { label: "教育实验学院", value: "教育实验学院" },
          { label: "国际教育学院", value: "国际教育学院" },
          { label: "国家保密学院", value: "国家保密学院" },
          { label: "马克思主义学院", value: "马克思主义学院" },
          { label: "微电子学院", value: "微电子学院" },
          { label: "网络空间安全学院", value: "网络空间安全学院" },
          { label: "民航学院", value: "民航学院" },
          { label: "生态环境学院", value: "生态环境学院" },
        ],
      },
    },
    {
      name: "GENDER",
      key: GENDER,
      label: getValue([INSERT, GENDER]),
      //validator: "",
      rules:[{ required: true, message: "该项不能为空" }],
      tooltip: getValue(["tooltips", INSERT, GENDER]),
      Component: Select,
      props: {
        placeholder: "选择性别",
        disabled: isEdit,
        options: [
          { label: "男", value: "male" },
          { label: "女", value: "female" },
        ],
      },
    },
    {
      name: "SUPERVISOR",
      key: SUPERVISOR,
      label: getValue([INSERT, SUPERVISOR]),
      //validator: "",
      rules:[{ required: true, message: "该项不能为空" }],
      tooltip: getValue(["tooltips", INSERT, SUPERVISOR]),
      Component: Input,
      props: {
        prefix: <UserOutlined />,
      },
    },
    {
      name: "SCENE",
      key: SCENE,
      label: getValue([INSERT, SCENE]),
      //validator: "",
      rules:[{ required: true, message: "该项不能为空" }],
      tooltip: getValue(["tooltips", INSERT, SCENE]),
      Component: Cascader,
      props: {
        placement: "topRight",
        showArrow: true,
        // onChange:setSelectedItems,
        options: scene,
        multiple: true,
      },
    },
  ];

  return (
    <Layout>
      <Form
        {...layout}
        form={form}
        ref={formRef}
        name="control-ref"
        style={{ maxWidth: 600 }}
        initialValues={info}
      >
        {components.map(
          ({
            name,
            key,
            label,
            validator,
            required,
            tooltip,
            Component,
            props,
            rules,
          }: any) => {
            return (
              <Form.Item
                name={name}
                label={label}
                required={required}
                tooltip={tooltip}
                rules={rules}
              >
                {Wrapper({
                  children: Component,
                  options: props,
                  required: true,
                })}

              </Form.Item>
            );
          }
        )}

        <Form.Item {...tailLayout} key="submit">
          <Button type="primary" htmlType="submit" onClick={onFinish}>
            Submit
          </Button>
          <span style={{ padding: "20px" }}></span>
          <Button htmlType="button" onClick={onReset}>
            Reset
          </Button>
        </Form.Item>
      </Form>
    </Layout>
  );
};

const validate = (name: string) => {
  const validators = {
    zh: [
      {
        validator: (_: any, value: any) => {
          // 正则校验value为中文
          const reg = /^[\u4e00-\u9fa5]+$/;
          if (reg.test(value)) {
            return Promise.resolve();
          }
          return Promise.reject(new Error("请输入中文"));
        },
      },
    ],
  } as any;

  return validators.hasOwnProperty(name) ? validators[name] : [];
};

export default InsertInfo;
